<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="订单搜索" prop="skuName" >
        <el-input
            v-model="queryParams.skuName"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter="handleQuery"
            style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
            v-model="queryParams.dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格区域 -->
    <el-table
        v-loading="loading"
        :data="orderList"
        style="width: 100%"
        :cell-style="{padding: '12px 0'}"
    >
      <el-table-column label="序号" align="center" width="60" type="index" />
      <el-table-column label="订单编号" align="center" prop="orderNo" min-width="150" />
      <el-table-column label="商品名称" align="center" prop="skuName" min-width="120" />
      <el-table-column label="订单金额" align="center" width="100">
        <template #default="scope">¥{{ scope.row.amount }}</template>
      </el-table-column>
      <el-table-column label="设备编号" align="center" prop="innerCode" min-width="120" />
      <el-table-column label="订单状态" align="center" width="100">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单日期" align="center" width="180">
        <template #default="scope">
          {{ parseTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100">
        <template #default="scope">
          <el-button link type="primary" @click="handleView(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" v-model="detailVisible" width="50%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ currentOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="商品名称">{{ currentOrder.skuName }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">¥{{ currentOrder.amount }}</el-descriptions-item>
        <el-descriptions-item label="设备编号">{{ currentOrder.innerCode }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusTagType(currentOrder.status)">
            {{ getStatusText(currentOrder.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="订单日期">{{ parseTime(currentOrder.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="点位地址">{{ currentOrder.addr }}</el-descriptions-item>
        <el-descriptions-item label="支付类型">
          {{ currentOrder.payType === 1 ? '支付宝' : '微信' }}
        </el-descriptions-item>
        <el-descriptions-item label="操作">
          <template #default="scope">
            <!-- 支付完成的订单显示退款按钮 -->
            <el-button
                v-if="currentOrder.status === 1"
                link
                type="primary"
                @click="handleRefund"
            >
              退款
            </el-button>
            <!-- 待支付的订单显示关闭订单按钮 -->
            <el-button
                v-if="currentOrder.status === 0"
                link
                type="danger"
                @click="handleCancelOrder"
            >
              关闭订单
            </el-button>
            <span v-if="currentOrder.status !== 0 && currentOrder.status !== 1">无操作</span>
          </template>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<script setup>
import { listOrder } from "@/api/manage/order";
import { parseTime } from "@/utils/ruoyi";

const { proxy } = getCurrentInstance();
const dateRange = ref([]);

const orderList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const detailVisible = ref(false);
const currentOrder = ref({});
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  searchKey: '',
  dateRange: []
});

// 状态映射
const statusMap = {
  0: { text: '待支付', type: 'warning' },
  1: { text: '支付完成', type: 'primary' },
  2: { text: '出货成功', type: 'success' },
  3: { text: '出货失败', type: 'danger' },
  4: { text: '已取消', type: 'info' }
};

/** 获取状态文本 */
function getStatusText(status) {
  return statusMap[status]?.text || status;
}

/** 获取状态标签类型 */
function getStatusTagType(status) {
  return statusMap[status]?.type || '';
}
function cancel() {
  detailVisible.value = false;
}

/** 查询订单列表 */
function getList() {
  loading.value = true;
  listOrder(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查看详情 */
function handleView(row) {
  currentOrder.value = row;
  detailVisible.value = true;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.$refs.queryRef.resetFields();
  // 强制清空日期范围（部分场景下resetFields可能不生效）
  queryParams.value.dateRange = [];
  queryParams.value.pageNum = 1;
  getList();
}
import { updateOrder } from "@/api/manage/order";

// 退款方法
// 退款方法
// 退款方法
function handleRefund() {
  // 先检查订单状态
  if (currentOrder.value.status !== 1) {
    proxy.$modal.msgError("只有已支付的订单才能退款");
    return;
  }

  proxy.$modal.confirm('是否确认对此订单进行退款操作？').then(() => {
    const params = {
      orderNo: currentOrder.value.orderNo,
      id: currentOrder.value.id,
      status: 4,

    };
    console.log("发送的退款参数:", params);
    updateOrder(params);
  }).then(() => {
    proxy.$modal.msgSuccess("退款成功");
    currentOrder.value.status = 4;
    getList();
    detailVisible.value = false;
  }).catch((error) => {
    console.error("退款失败:", error);
    // 显示后端返回的错误信息
    const errorMsg = error.response?.data?.msg || "退款失败，请稍后重试";
    proxy.$modal.msgError(errorMsg);
  });
}

// 取消订单方法
function handleCancelOrder() {
  proxy.$modal.confirm('是否确认对此订单进行取消操作？').then(() => {
    // 方式1: 直接传递参数对象
    return updateOrder({
      orderNo: currentOrder.value.orderNo,
      status: 4
    });
  }).then(() => {
    proxy.$modal.msgSuccess("取消成功");
    currentOrder.value.status = 4;
    getList();
    detailVisible.value = false;
  }).catch(() => {});
}


getList();
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.el-form-item {
  margin-bottom: 12px;
}
:deep(.el-table .cell) {
  white-space: nowrap;
}
</style>